<template>

  <div id="app" class="container">

    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item >手动任务</el-breadcrumb-item>

      </el-breadcrumb>
    </div>
    <el-row :gutter="30" class="row-gutter">
      <el-col :span="16" class="doc-column file-selection">
        <div class="file-selection-container">
          <div>
          <el-cascader
            v-model="selectedFileId"
            :options="fileOptions"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择文件"
            class="file-selector"
            @change="handleFileChange"
            transition="fade"
            :disabled="isCascaderDisabled"> <!-- 绑定禁用属性 --> >
            <template slot-scope="{ node, data }">
              <span :class="{ 'is-leaf': !node.children }">{{ node.label }}</span>
            </template>
          </el-cascader>
          </div>
          <div  class="select-container">

<!--          <el-select  size="medium"-->
<!--                      v-model="example"-->
<!--                      multiple placeholder="请选择执行条件"-->
<!--                      :disabled="isSelectDisabled"-->
<!--                      @change="handleSelectChange">-->
<!--            <el-option-->
<!--              v-for="item in exampleData"-->
<!--              :key="item.id"-->
<!--              :label="item.example"-->
<!--              :value="item.example">    &lt;!&ndash;可能需要修改&ndash;&gt;-->
<!--            </el-option>-->
<!--          </el-select>-->
            <el-select v-model="selectedName"
                       placeholder="请选择指标集"
                       :disabled="isSelectDisabled"
                       @change="handleNameChange">
              <el-option
                v-for="item in names"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <div v-if="selectedName" class="select-wrapper">
              <el-select v-model="selectedIndicators"
                         multiple placeholder="请选择指标"
                         :disabled="isSelectDisabled"
                         @change="handleSelectChange">
                <el-option
                  v-for="indicator in indicatorForSelectedName"
                  :key="indicator"
                  :label="indicator"
                  :value="indicator">
                </el-option>
              </el-select>
            </div>
            </div>
          <div>
            <el-button
              :size="isLoading ? 'mini' : 'mini'"
              :type="isLoading ? 'primary' : 'primary'"
              :loading="isLoading"
              style="width: 100px;height: 40px"
              @click="callCHATGPT"
            >
              {{ isLoading ? '正在提取' : '开始提取' }}
            </el-button>
            </div>
<!--          <div>-->
<!--            <el-button size="small" @click='check'>测试</el-button>-->
<!--          </div>-->
        </div>
        <div class="content-display">
          <el-scrollbar v-if="selectedFileContent" >
            <pre class="file-content">{{ selectedFileContent }}</pre>
          </el-scrollbar>
          <div v-else class="empty-content-placeholder">
            <div class="placeholder-content">内容展示区域</div>
          </div>
        </div>
      </el-col>

      <el-col :span="8" class="doc-column result-display">
        <div class="title-bar">结果展示</div>
        <div v-if="tableVisible">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            class="table-container"
            highlight-current-row
            row-class-name="table-row-class"
            :header-cell-style="{'background-color': '#ddd'}">
            <el-table-column
              prop="key"
              align="center"
              label="指标"
              width="100">
            </el-table-column>
            <el-table-column
              prop="value"
              align="center"
              label="结果">
            </el-table-column>
          </el-table>
        </div>
        <div v-if="errorVisible" class="error-container">
          <div class="error-message-box">
            <div class="error-message">{{ this.resData }}</div>
          </div>
          <div class="error-icon">
            <i class="el-icon-warning">模型输出结果无法解析</i>
          </div>
        </div>
      </el-col>
    </el-row>


  </div>
</template>
<script>
  import axios from "axios";

  export default {
    data() {
      return {
        selectedName: '',
        selectedIndicators: [],
        names: [],
        indicatorForSelectedName: [],
        indicatorListData:[],
        isCascaderDisabled: false, // 初始禁用级联选择器
        isSelectDisabled: false, // 初始禁用选择框
        isLoading: false,
        errorVisible:false,
        tableVisible:false,
        data1:'',
        inputText: '',
        chatLog: [],

        content:[],

        // 请求数据参数
        formInline: {
          name:'',
          page: 1,
          limit: 10,
          fileName: '',
          isLock: ''
        },
        // 模型请求参数
        modelPara:{
          fileId:'',
          exampleId:'',
        },
        selectedTag: '',
        fileData:[],
        filteredFiles:[],
        uniqueTags: [], // 用于存储所有唯一的标签
        selectedFileId:'', // 用于存储当前选中的文件的id
        selectedFileContent:'',//文件内容
        exampleData:[],//条件数据

        example:'', // 执行条件

        resData:[], // 存放结果
        tableData:[], // 用于渲染
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        },
      };
    },
    created() {

      this.data1 = localStorage.getItem('userId')
      this.getUnStructSourceData();
      this.getExample();
      this.getSearchPage();


    },
    computed: {

        fileOptions() {
          const tagMap = {};
          this.fileData.forEach(item => {
            if (!tagMap[item.tag]) {
              tagMap[item.tag] = {
                label: item.tag,
                value: item.tag,
                children: []
              };
            }
            tagMap[item.tag].children.push({
              label: item.fileName,
              value: item.id
            });
          });
          return Object.values(tagMap);

        },

    },
    watch: {
      selectedFileId(newVal, oldVal) {
        if (newVal !== oldVal && newVal !== null) {
          // 当selectedFileId发生变化并且不为null时，清空chatLog
          this.resData = [];
          this.tableVisible = false;
          this.errorVisible = false
          // 如果需要，可以在这里调用callCHATGPT方法
          // this.callCHATGPT();
        }
      }
    },
    methods: {
      handleSelectChange() {
        // 当选择的 item.example 发生改变时，清空表格数据
        this.tableData = [];
        this.resData = [];
        this.tableVisible = false;
        this.errorVisible = false;
      },
      check() {
        this.resData = "{\n" +
          "  \"占地面积\": null,\n" +
          "  \"项目总投资\": null,\n" +
          "  \"项目代码\": null\n" +
          "}";
          const parsedInputText = JSON.parse(this.resData);
          if (!parsedInputText) {
            this.errorVisible = true;
          } else {
            this.tableVisible = true;
            const parsedInputText = JSON.parse(this.resData);
            this.tableData = Object.entries(parsedInputText).map(([key, value]) => ({
              key,
              value
            }));
          }
      },
      handleFileChange(value) {
        if (value.length === 2) {
          // value[1] 是选中的文件id
          const fileId = value[1];
          const selectedFile = this.fileData.find(file => file.id === fileId);
          if (selectedFile) {
            this.selectedFileContent = selectedFile.content;
          }
        }
      },
      handleNameChange() {
        // 当name改变时，重置hobbies为对应name的所有hobby
        const selectedItem = this.indicatorListData.find(item => item.name === this.selectedName);
        if (selectedItem) {
          this.selectedIndicators = [...selectedItem.indicators];
          this.indicatorForSelectedName = selectedItem.indicators;
        } else {
          this.selectedIndicators = [];
          this.indicatorForSelectedName = [];
        }
        this.tableData = [];
        this.tableVisible = false;
      },
      getSearchPage(formInline) {
        this.logining = true
        let url = this.$global.javaUrl +"/indicatorList/list"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              name:this.formInline.name,
              pageNum: this.formInline.page,
              pageSize:this.formInline.limit,

            }
        }
        axios.get(url, config).then(response=>{
          this.indicatorListData = response.data.data.rows
          this.pageparm.total=response.data.data.records
          this.indicatorListData.forEach(item => {
            item.indicators = item.indicators.split(',');
          });
          this.names = this.indicatorListData.map(item => item.name);
          console.log(this.names)
        })

      },
        callCHATGPT() {
          if (this.selectedFileContent === '') {
            this.showError('请选择文件！');
            return;
          }
          if (this.selectedIndicators.length ===0 ) {
            this.showError('请选择指标！');
            return;
          }

          this.isCascaderDisabled = true; // 禁用级联选择器
          this.isSelectDisabled = true; // 禁用选择框
          this.isLoading = true; // 开始时设置加载状态
          this.resData = '';

          const examplePrompt = `请逐步思考，根据以下文本，请准确提取出文本中的[${this.selectedIndicators}]的信息。
          输出结果严格遵守以下要求：结果都封装在一个完整的JSON格式里面，[${this.selectedIndicators}]每一项是键，提取出的结果是属性值。
          若文本中未找到[${this.selectedIndicators}]某项的值，则该属性值设为null，一定不要编造数据和文本。\n`;

          const prompt1 = `${examplePrompt}\n${this.selectedFileContent}`;

          console.log("prompt：" + prompt1);

          const url = this.$global.javaUrl + "/indicatorConfig/chatTest";
          const userId = localStorage.getItem('userId');


          const config = {
            headers: {
              'user': userId
            },

          };

          axios.post(url,{prompt:prompt1}, config)
            .then(response => {
              this.resData = response.data.data;
              console.log(this.resData)
              this.isLoading = false; // 请求成功，结束加载状态
              this.isCascaderDisabled = false;
              this.isSelectDisabled = false;
                const parsedInputText = JSON.parse(this.resData);
                if (!parsedInputText) {
                  this.errorVisible = true;
                } else {
                  this.tableVisible = true;
                  const parsedInputText = JSON.parse(this.resData);
                  this.tableData = Object.entries(parsedInputText).map(([key, value]) => ({
                    key,
                    value
                  }));
                  // 处理解析成功的数据
                }
              console.log("后端结果："+this.resData)
              console.log("表单数据："+this.tableData);
            })
            .catch(error => {
              console.error('请求失败：', error);
              this.showError('请求失败，请稍后再试！');
              this.isLoading = false; // 请求失败，结束加载状态
              this.isCascaderDisabled = false;
              this.isSelectDisabled = false;
            });
      },
      showError(message) {
        this.$message.error(message);
      },
      getUnStructSourceData(){
        this.logining = true
        this.fileData = []
        let url = this.$global.javaUrl+"/dataSource/listUnStruct"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params: {
            pageNum: this.formInline.page,
            pageSize:1000,
            tagId:0

          }
        }

        axios.get(url, config).then(response=>{
          this.UnStructSourceData = response.data.data.rows
       //   console.log(JSON.stringify(response.data.data.rows , null, 2));
          // 以格式化的方式显示对象内容
          for(var i = 0; i < this.UnStructSourceData.length; i++) {
            this.fileData.push({
              id: this.UnStructSourceData[i].id,
              tag: this.UnStructSourceData[i].tag,
              fileName: this.UnStructSourceData[i].fileName,
              content: this.UnStructSourceData[i].content
            });
          }
          this.uniqueTags = [new Set(this.fileData.map(item => item.tag))];



        })

      },
      // 获取执行条件
      getExample() {
        this.logining = true
        let url = this.$global.javaUrl+"/target/list"
        let config = {
          headers:
            {
              //'Content-Type':'application/json',
              'user' : localStorage.getItem('userId')
            },
          params:
            {
              name:'',
              tag:'指标',
              pageNum: '1',
              pageSize:'100',

            }
        }
        axios.get(url, config).then(response=>{
          this.exampleData = response.data.data.rows


        })
      },
      selectedFile() {
        return this.fileData.find(file => file.id === this.selectedFileId);
      },
    },
  };
</script>

<style scoped>
  .breadcrumb{
    margin-bottom: 10px; /* 可选：添加底部外边距，以便与其他元素分隔 */
  }

  /* 全局样式 */
  .row-gutter {
    background-color: #f5f7fa;
  }

  .file-selection-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .file-selector {
    width: 310px;
    margin-right: 2px;
  }

  .example-selector {
    width:  300px;
  }

  .content-display {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0, 0, 0.1);
    margin-top: 20px;
    height: 400px;
  }

  .file-content {
    background-color: #f9f9f9;
    padding: 10px;
    border-radius: 4px;
    overflow-y: auto; /* 添加垂直滚动条 */
    white-space: pre-wrap;
    font-family: 'Courier New', monospace;
    font-size: 14px;
    height: 360px; /* 设置高度为460px */
  }

  .empty-content-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400px;
  }
  .select-container {
    display: flex;
    align-items: center; /* Optional: Vertically align the selects */
  }

  .select-wrapper {
    margin-left: 3px; /* Optional: Space between selects */
  }
  .placeholder-content {
    color: #999;
    font-size: 16px;
  }

  .result-display {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
  }

  .title-bar {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
  }

  .table-container {
    overflow: auto;
  }

  .table-row-class {
    transition: background-color 0.3s;
  }

  .table-row-class:hover {
    background-color: #f0f0f0;
  }

  .error-container {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    width: 100%; /* 或者你需要的宽度 */
  }

  .error-message-box {
    border: 1px solid #e0d5d5;
    background-color: rgba(250, 235, 215, 0.25);
    border-radius: 5px;
    padding: 20px; /* 增加内边距来使文字更居中，并且看起来更舒适 */
    margin-bottom: 10px; /* 底部外边距，为 error-icon 留出空间 */
    display: flex; /* 使用flex布局来垂直和水平居中内容 */
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    /* 你可以根据需要设置宽度和高度 */
    width: 300px;
    height: auto; /* 让高度自动调整以容纳内容 */
  }

  .error-message {
    /* 如果有需要，可以添加更多样式 */
  }

  .error-icon {
    position: relative; /* 不需要绝对定位了，因为现在是放在 flex 容器底部 */
    width: 100%; /* 宽度100%确保图标横跨整个容器 */
    text-align: center; /* 水平居中图标和文本 */
  }

  .el-icon-warning {
    font-size: 16px; /* 设置图标的大小 */
    color: red; /* 设置图标的颜色 */
    /* 这里可以添加图标的样式，比如颜色、大小等 */
  }
</style>
